package br.ufrj.dcc.smarthotel.controls;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import br.ufrj.dcc.smarthotel.R;
import br.ufrj.dcc.smarthotel.activities.SignUpActivity;
import br.ufrj.dcc.smarthotel.entities.User;

public class SignUpControl extends Control {
	SignUpActivity activity;
	
	
	public SignUpControl(SignUpActivity activity) {
		this.activity = activity;
	}
	
	public void SignUp () {
		if (this.isValidUser()) {
			User user = this.getUser();
			
			Map<String, Object> kvPairs = new HashMap<String, Object>();
			
			kvPairs.put("user", user);
			
			String resultLocation = this.doPost("user", kvPairs);
			
			if (resultLocation != null) {
				this.activity.showQuickMessage(R.string.msg_UserSignedUpSuccefully);
				this.activity.finish();
			}
			else {
				this.activity.showQuickMessage(R.string.msg_UserSignUpFailed);
			}
		}
	}
	
	private boolean isValidUser () {
		boolean valid = true;
		
		if (this.activity.getName() == "") {
			this.activity.showQuickMessage(R.string.msg_InvalidName);
			valid = false;
		}
		
		if (this.activity.getEmail() == "") {
			this.activity.showQuickMessage(R.string.msg_InvalidEmail);
			valid = false;
		}
		
		if (this.activity.getPassword() == "" || !this.activity.getConfirmPassword().equals(this.activity.getPassword())) {
			this.activity.showQuickMessage(R.string.msg_InvalidPassword);
			valid = false;
		}
		
		if (this.activity.getBirthDate().after(new Date(System.currentTimeMillis()))) {
			this.activity.showQuickMessage(R.string.msg_InvalidBirthDate);
			valid = false;
		}
		
		return valid;
	}
	
	public User getUser() {
		User user = new User();
		
		user.setBirthDate(this.activity.getBirthDate());
		user.setEmail(this.activity.getEmail());
		user.setIdentification(this.activity.getIdentification());
		user.setIdentificationType(this.activity.getIdentificationType());
		user.setName(this.activity.getName());
		user.setPassword(this.activity.getPassword());
		user.setPhone(this.activity.getPhone());
		
		return user;
	}
}
